import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../components/Login.vue'
import Home from '../components/Home.vue'
import WelCome from '../components/WelCome.vue'
import Users from '../components/user/Users.vue'
import Questionnaire from '../components/questionnaire/Questionnaire.vue'
import Dequetionnaire from '../components/questionnaire/DoQuestionnaire.vue'
import Register from '../components/Register.vue'
import Statistics from '../components/questionnaire/Statistics.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    // redirect: '/home'
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: {
      title: '登录'
    }
  },
  {
    path: '/register',
    name: 'Register',
    component: Register,
    meta: {
      title: '注册'
    }
  },
  {
    path: '/home',
    name: 'Home',
    component: Home,
    redirect: '/welcome',
    children: [
      { path: '/welcome', component: WelCome },
      { path: '/users', component: Users },
      { path: '/questionnaire', component: Questionnaire }
    ],
    meta: {
      title: '首页'
    }
  },
  {
    path: '/doquestionnaire/:questionnaireId',
    name: 'Dequetionnaire',
    component: Dequetionnaire,
    props: true,
    meta: {
      title: '问卷填写'
    }
  },
  {
    path: '/statistics/:questionnaireId',
    name: 'Statistics',
    component: Statistics,
    props: true,
    meta: {
      title: '答案统计'
    }
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 在路由对象上挂载路由导航守卫
router.beforeEach((to, from, next) => {
  // to 将要访问的路径
  // from 代表从哪个路径跳转而来
  // next 是一个函数，表示放行
  // next() 放行 next('/login') 强制跳转
  if (to.path === '/login' || to.path === '/register') return next() // 如果是登录或者注册页面就直接放行
  const tokenStr = window.sessionStorage.getItem('token') // 其他页面 需要获取token 并token才能访问
  if (!tokenStr) return next('/login') // 如果没有token 强制跳转到登录页
  // 如果token存在，直接放行
  // 设置页面标题
  // if (to.meta.title) {
  //   document.title = to.meta.title
  // }
  next()
})

export default router
